package com.wen.pay;

import com.google.gson.internal.LinkedHashTreeMap;
import com.tencent.mm.sdk.modelpay.PayReq;

import java.util.Map;
import java.util.Random;

import cn.wen.core.utils.MD5;

/**
 * 微信生成签名的工具类
 */

public class WXSignUtil {
    /**
     * 微信----生成支付签名
     */
    public static void genPayReq(PayReq payReq, String prepayId) {
        payReq.appId = Constants.APP_ID;
        payReq.partnerId = Constants.MCH_ID;
        payReq.prepayId = prepayId;
        payReq.packageValue = "Sign=WXPay";
        payReq.nonceStr = genNonceStr();
        payReq.timeStamp = String.valueOf(genTimeStamp());
        Map<String, String> maps = new LinkedHashTreeMap<>();
        maps.put("appid", payReq.appId);
        maps.put("noncestr", payReq.nonceStr);
        maps.put("package", payReq.packageValue);
        maps.put("partnerid", payReq.partnerId);
        maps.put("appid", payReq.appId);
        maps.put("prepayid", payReq.prepayId);
        maps.put("timestamp", payReq.timeStamp);
        payReq.sign = genAppSign(maps);
    }

    private static String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000))
                .getBytes());
    }

    /**
     * 时间戳
     */
    private static long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    private static String genAppSign(Map<String, String> maps) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> me : maps.entrySet()) {
            sb.append(me.getKey());
            sb.append('=');
            sb.append(me.getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(Constants.API_KEY);
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return appSign;
    }
}
